from django.shortcuts import render
from django.views import View
from django import http
from alipay import AliPay
from django.conf import settings
import os
from orders.models import OrderInfo

from meiduo_mall.utils.response_code import RETCODE
from payments.models import Payment


class GetPayUrlView(View):
    def get(self, request, order_id):
        # 验证订单编号
        try:
            order = OrderInfo.objects.get(pk=order_id)
        except:
            return http.Http404('订单编号无效')
        # 创建支付宝对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        # 生成支付的参数
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城-订单支付',
            return_url=settings.ALIPAY_RETURN_URL
        )
        # 拼接最终的支付地址
        alipay_url = settings.ALIPAY_URL + '?' + order_string
        # 响应
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'alipay_url': alipay_url
        })


class AlipayStatusView(View):
    def get(self, request):
        # 接收支付宝返回的数据,querydict转dict
        data = request.GET.dict()
        from pprint import pprint  # 格式化打印
        pprint(data)
        '''
        {
        'app_id': '2016092800618034',
         'auth_app_id': '2016092800618034',
         'charset': 'utf-8',
         'method': 'alipay.trade.page.pay.return',
         'out_trade_no': '20190608205021000000001',
         'seller_id': '2088102177693611',
         'sign': 'V6GfpYTr1QiOiRsiRgtFF0FiNwmtby00eEm1aKDttgAtEsVmGsOw404+mzHwl/Sqnak1k5XXXXZRl3B7jxG19vHAhy4jenbNrH2DgSVrLBofLzW62GoBRBskI24RRYvJm1t51AHER9zN9zPXDxfEtjo4s7fDWYY2QW8p2bYCP99YUbT3plX/om6WRMCrYhNnAwve9Me21Uw4EqeGhg5GRMb4pdPMnRg7Us4thQ/Qg4JWnH6Dp3qs12lDCebhyLWGrxK+f/K7DBexApsYjlR8avhWYSiWNAGzLXkM5W145gLerxNlL1Xqe5Zm51L3k/shuKjkYpPoz+5KUL1Nj2oixQ==',
         'sign_type': 'RSA2',
         'timestamp': '2019-06-09 20:14:44',
         'total_amount': '35750.00',
         'trade_no': '2019060922001415141000019440',
         'version': '1.0'
        }
        '''
        signature = data.pop('sign')
        # 验证是否支付成功
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/app_private_key.pem'),
            alipay_public_key_path=os.path.join(settings.BASE_DIR, 'libs/alipay/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )
        success = alipay.verify(data, signature)
        if not success:
            return http.HttpResponseBadRequest('支付失败，请重新支付。')

        # 如果支付成功验证支付的状态
        order_id = data.get('out_trade_no')
        trade_no = data.get('trade_no')
        # 1.保存支付宝流水号
        Payment.objects.create(
            order_id=order_id,
            trade_id=trade_no
        )
        # 2.修改订单状态为待发货
        OrderInfo.objects.filter(pk=order_id).update(status=1)
        # 修改订单状态，保存支付宝流水号
        context = {
            'trade_no': data.get('trade_no')  # 支付宝流水号
        }
        return render(request, 'pay_success.html', context)
